package org.utils;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;

import com.sojoys.artifact.constant.ArtifactErrorCode;
import com.sojoys.artifact.exception.AbstractLogicModelException;
import com.sojoys.artifact.factory.session.ISession;
import com.sojoys.artifact.manager.MessageManager;

/**
 * @author : DengYing
 * @CreateDate : 2017年12月13日 下午12:58:49
 * @Description ：Please describe this document
 */
public class AsyncUnit {
	// 异步执行BO逻辑
	public static void runAsyncBO(final ISession session,final short code,Runnable runnable) {
		CompletableFuture.runAsync(runnable).exceptionally(ex -> {
			if (ex.getCause() instanceof AbstractLogicModelException) {
				AbstractLogicModelException logicEx = (AbstractLogicModelException) ex;
				session.sendMessage(MessageManager.me().create(code, logicEx.getCode()));
			} else {
				session.sendMessage(MessageManager.me().create(code, ArtifactErrorCode.UNKNOWN_ERROR));
			}
			return null;
		});
	}
	
	public static void runAsyncBO(final ISession session,final short code,Runnable runnable,Executor executor) {
		CompletableFuture.runAsync(runnable, executor).exceptionally(ex -> {
			if (ex.getCause() instanceof AbstractLogicModelException) {
				AbstractLogicModelException logicEx = (AbstractLogicModelException) ex;
				session.sendMessage(MessageManager.me().create(code, logicEx.getCode()));
			} else {
				session.sendMessage(MessageManager.me().create(code, ArtifactErrorCode.UNKNOWN_ERROR));
			}
			return null;
		});
	}
}
